package com.dongdongshop.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import com.dongdongshop.mapper.TbAddressMapper;
import com.dongdongshop.mapper.TbOrderItemMapper;
import com.dongdongshop.mapper.TbOrderMapper;
import com.dongdongshop.pojo.TbAddress;
import com.dongdongshop.pojo.TbOrder;
import com.dongdongshop.pojo.TbOrderItem;
import com.dongdongshop.service.TbItemService;
import com.dongdongshop.service.TbOrderService;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@com.alibaba.dubbo.config.annotation.Service
public class TbOrderServiceImpl implements TbOrderService {

    @Autowired
    private TbOrderMapper tbOrderMapper;

    @Autowired
    private TbAddressMapper tbAddressMapper;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    private TbOrderItemMapper tbOrderItemMapper;

    @Reference
    private TbItemService tbItemService;

    @Override
    public TbAddress getAddressById(Long id) {
        return tbAddressMapper.selectByPrimaryKey(id);
    }

    @Override
    public void insert(TbOrder tbOrder) {
        tbOrderMapper.insertSelective(tbOrder);
    }

    @Override
    public void updateBYOTN(String tradeNo, String outTradeNo) {

        tbOrderMapper.updateBYOTN(tradeNo,outTradeNo);
        TbOrder tbOrder = tbOrderMapper.selectByTrade(tradeNo);
        TbOrderItem tbOrderItem = tbOrderItemMapper.selectByTrade(tradeNo);
        TbOrder tbOrder1 = new TbOrder();
        tbOrder1.setUserId(tbOrder.getUserId());
        tbOrder1.setPayment(tbOrder.getPayment());

//        tbItemService.updateStockCount(tbOrderItem.getItemId(),tbOrderItem.getNum());
        // 发送事务消息
        String s = JSONObject.toJSONString(tbOrder1);
        Message message = MessageBuilder.withPayload(s).build();
        rocketMQTemplate.sendMessageInTransaction("tx-group", "tx-score-topic", message, s);
    }

    @Override
    public List<TbOrder> selectOrder() {
        return tbOrderMapper.selectByExample(null);
    }
}
